package club.cearnach.web.controller.movie;

import club.cearnach.api.exception.UserException;
import club.cearnach.api.service.IVerificationCodeService;
import club.cearnach.api.vo.ResultVO;
import club.cearnach.security.vcode.exception.VerificationModeNotFoundException;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.Callable;

/**
 * @author 阮胜
 * @date 2018/6/3 15:15
 */
@Controller
@Slf4j
@RequestMapping("/user/verify")
@Api(tags = "验证码控制层")
public class VerificationCodeController {
    private static final String SEND_V_CODE_SUCCESS = "发送验证码成功,请注意查收!";
    private final IVerificationCodeService verificationCodeService;

    public VerificationCodeController(IVerificationCodeService verificationCodeService) {
        this.verificationCodeService = verificationCodeService;
    }

    @GetMapping("/create")
    @ResponseBody
    public Callable<ResultVO> create(HttpServletRequest req) {
        return () -> {
            ResultVO resultVO = new ResultVO();
            try {
                verificationCodeService.createAndSend(req);
                resultVO.setSuccess(true);
                resultVO.setMsg(SEND_V_CODE_SUCCESS);
            } catch (VerificationModeNotFoundException | UserException | MessagingException e) {
                resultVO.setSuccess(false);
                resultVO.setMsg(e.getMessage());
                log.error(e.getMessage());
            }
            return resultVO;
        };
    }
}
